# coding:utf-8

import os
import time
import json
import zipfile
from openpyxl.reader.excel import load_workbook


def openfile(file_path, xlsx_name, exportzipname):

    dirlist = os.listdir(file_path)
    img_dict = {}

    # 创建文件夹 并写入图片
    print "---  new folder...  ---"
    today_str = time.strftime("%Y-%m-%d", time.localtime())
    path = file_path + '/myfile/' + today_str
    folder = os.path.exists(path)
    if not folder:  # 判断是否存在文件夹如果不存在则创建为文件夹
        os.makedirs(path)
        print "---  new folder ok  ---"
    else:
        print "folder exists"

    for fname in dirlist:
        if fname.endswith('.jpg'):
            img_path = path + '/' + fname
            fw = open(img_path, 'wb+')
            fr = open(file_path + '/' + fname, 'rb')
            content = fr.read()
            fw.write(content)
            fw.close()
            fr.close()
            img_dict[os.path.splitext(fname)[0]] = today_str + '/' + fname

    # 读取xlxs
    wb = load_workbook(file_path + '/' + xlsx_name)
    # 取出第一张表
    sheetnames = wb.get_sheet_names()
    ws = wb.get_sheet_by_name(sheetnames[0])

    # 读取表的内容
    rows = ws.rows
    columns = ws.columns
    personList = []
    id = 0
    # 跳过读取第一行
    rows.next()
    # 读取内容
    for row in rows:
        line = [col.value for col in row]
        person = {}
        id += 1
        if line[4] == None:
            break

        person['id'] = id
        person['company_id'] = 3
        person['subject_type'] = 0
        person['birthday'] = None
        person['entry_date'] = None
        person['email'] = u''
        person['department'] = u''
        person['phone'] = u''

        person['name'] = line[1] if line[1] != None else u''
        if line[4] != None:
            person['photos'] = [img_dict.get(str(line[4]), None) if img_dict.get(str(line[4]), None) != None else '']
            person['job_number'] = line[4]


        description_type = u'0'
        if line[7] != None:
            if line[7] == u'新训':
                description_type = u'1'
            if line[7] == u'复训':
                description_type = u'2'
            if line[7] == u'延长复训':
                description_type = u'3'

        person['description'] = description_type
        person['title'] = line[8] if line[8] != None else u''
        person['remark'] = line[9] if line[9] != None else u''


        personList.append(person)

    # 写入json数据
    f = open(file_path + '/myfile/index.json', 'w')
    f.write(json.dumps(personList))
    f.close()
    # 压缩成zip文件
    zip_dir(file_path + '/myfile/', exportzipname)


def zip_dir(dirname, zipfilename):
    filelist = []
    if os.path.isfile(dirname):
        filelist.append(dirname)
    else:
        for root, dirs, files in os.walk(dirname):
            for name in files:
                filelist.append(os.path.join(root, name))

    zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)
    for tar in filelist:
        arcname = tar[len(dirname):]
        # print arcname
        zf.write(tar, arcname)
    zf.close()


def read_config():
    f = open('config.json', 'r')
    info = json.load(f)
    f.close()

    openfile(info['filepath'], info['xlsxname'], info['exportzipname'])


if __name__ == '__main__':
        # image = Image.open('tt.jpg')
        # data = recognize(image.tobytes())
        # print data
    # openfile('studentinfo')
    read_config()
